package com.victor.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.victor.dao.QuestionnaireDao;
import com.victor.entity.Option;
import com.victor.entity.Question;
import com.victor.service.QuestionnaireService;
import com.victor.utils.ExcelUtils;

@Service
public class QuestionnaireServiceImpl implements QuestionnaireService {

	@Autowired
	private QuestionnaireDao dao;

//	获取问卷调查列表
	@Override
	public List<Question> getAll() {
		return dao.getall();
	}

//	添加问题
	@Override
	public int addQuestion(Question question) {
		return dao.addQuestion(question);
	}

//	添加选项
	@Override
	public int addOptions(List<Option> options) {
		return dao.addOptions(options);
	}

//	修改问题
	@Override
	public int updateQuestion(Question question) {
		return dao.updateQuestion(question);
	}

//	通过问题id删除所有选项
	@Override
	public int deleteOption(Integer id) {
		return dao.deleteOption(id);
	}

	// 删除提问
	@Override
	public int deleteQuestion(int qid) {
		return dao.deleteQuestion(qid);
	}

//	批量导入问题
	@Override
	public String importQuestion(MultipartFile file, String adminid) {
		if (file.isEmpty()) {
			try {
				throw new Exception("文件不存在！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		List<List<Object>> listob = null;

		try {
			// 获取文件流
			listob = new ExcelUtils().getBankListByExcel(in, file.getOriginalFilename());

			// 该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
			for (int i = 0; i < listob.size(); i++) {
				List<Object> lo = listob.get(i);

				Question question = new Question();

				question.setAdminid(adminid);
				question.setQuestion(String.valueOf(lo.get(0)));
				// 添加问题
				dao.addQuestion(question);

				// 创建选项list
				List<Option> options = new ArrayList<Option>();
				Option option = new Option();

				for (int j = 1; j < lo.size(); j++) {
					option.setQuestionid(String.valueOf(question.getId()));
					option.setOption_name(String.valueOf(lo.get(j)));
					options.add(option);
					option = new Option();
				}

				// 添加选项
				dao.addOptions(options);
			}
			return "success";

		} catch (Exception e) {
			return "fail";
		}

	}
}
